package mobile

import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*

Entity transcation = null
if(params.transcationKey != '0') {
	def transcationId = params.transcationKey as int
	def transcationKey = ['TranscationE', transcationId] as Key
	transcation = datastore.get(transcationKey)
	use(groovy.time.TimeCategory) {
		int timeZoneHour = session.userTimeZoneHour as int
		int timeZoneMinute = session.userTimeZoneMinute as int
		def now = transcation.createdTime + timeZoneHour.hours + timeZoneMinute.minutes
		transcation.createdDateStg = now.format('yyyy-MM-dd')
		transcation.createdTimeStg = now.format('HH:mm')
	}

	def query = new Query('TranscationTagE')
	query.addSort('name', Query.SortDirection.ASCENDING)
	query.addFilter('transcationId', Query.FilterOperator.EQUAL, transcation.key.id)
	query.addFilter('userId', Query.FilterOperator.EQUAL, session.user.id)
	PreparedQuery preparedQuery = datastore.prepare(query)
	def ttentities = preparedQuery.asList( withLimit(Integer.MAX_VALUE) )

	def transcationTags = new StringBuilder()
	ttentities.each { transcationTag ->  transcationTags += "#$transcationTag.name " }

	request.transcationTags = transcationTags
}
else {
	transcation = new Entity('Transcation')
	transcation.amount = ''
	transcation.description = ''
	use(groovy.time.TimeCategory) {
		int timeZoneHour = session.userTimeZoneHour as int
		int timeZoneMinute = session.userTimeZoneMinute as int
		def now = new Date() + timeZoneHour.hours + timeZoneMinute.minutes
		transcation.createdDateStg = now.format('yyyy-MM-dd')
		transcation.createdTimeStg = now.format('HH:mm')
	}
	request.transcationTags = ''
}
request.transcation = transcation

request.title = 'Create/Edit Expenses'
request.view = 'expensesCreateOrEdit.gsp'

forward 'wydLayout.gsp'